package com.lion.hbase.api;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.lion.hbase.annotation.HField;
import com.lion.hbase.annotation.HTable;
import com.lion.hbase.exception.HbaseClientException;
import com.lion.hbase.util.ReflectUtil;
/**
 * 读取类注解
 * @author 李永曜
 * 2015年6月17日
 * @param <T>
 */
public class HTableInfo<T extends HbaseTableModel> {
	private String familyName;
	private String tableName;
	private Map<String, HFieldInfo> bind;
	/**
	 * 读取注解
	 * @param clazz
	 * @throws HbaseClientException
	 */
	public HTableInfo(Class<T> clazz) throws HbaseClientException {
		Annotation[] typeAnn = clazz.getAnnotations();
		bind = new HashMap<String, HFieldInfo>();
		// 获得类注解
		for (Annotation annotation : typeAnn) {
			if (annotation.annotationType() == HTable.class) {
				familyName = ((HTable) annotation).family();
				if (StringUtils.isBlank(familyName)) {
					throw new HbaseClientException("family can not be empty");
				}
				tableName = ((HTable) annotation).name();
				if (StringUtils.isBlank(tableName)) {
					tableName = clazz.getSimpleName();
				}
			}
		}
		// 获得成员变量注解
		List<Field> fields = ReflectUtil.getAllFields(clazz);
		getFieldAnnotation(fields);
	}
	/**
	 * 由下向上获得类及超类的成员变量
	 * @param fields
	 */
	public void getFieldAnnotation(List<Field> fields){
		for (Field field : fields) {
			String bindName = "";
			String format = "";
			for (Annotation annotation : field.getAnnotations()) {
				if (annotation.annotationType() == HField.class) {
					bindName = ((HField) annotation).value();
					format = ((HField) annotation).format();
				}
			}
			if (StringUtils.isBlank(bindName)) {
				bindName = field.getName();
			}
			if (StringUtils.isBlank(format)&&field.getType() == Date.class) {
				format = "yyyyMMddHHmmss";
			}
			bind.put(bindName, new HFieldInfo(field, bindName, format));
		}
	}

	public String getFamilyName() {
		return familyName;
	}

	public void setFamilyName(String familyName) {
		this.familyName = familyName;
	}

	public String getTableName() {
		return tableName;
	}

	public void setTableName(String tableName) {
		this.tableName = tableName;
	}

	public Map<String, HFieldInfo> getBind() {
		return bind;
	}

	public void setBind(Map<String, HFieldInfo> bind) {
		this.bind = bind;
	}

}
